<template>
  <div>
    <el-form ref="ruleForm" class="meal_form" :model="meal_list" :rules="rules" label-width="200px">
      <el-form-item label="租期设置:" prop="pact_type" style="line-height: 40px;">
        <el-checkbox-group v-if="draftId" v-model="submitForm.checkedLease">
          <el-checkbox v-for="val in lease_list" :key="val" :label="val" :disabled="enAble">{{ val }}</el-checkbox>
        </el-checkbox-group>
        <el-checkbox-group v-else v-model="checkedLease">
          <el-checkbox v-for="val in lease_list" :key="val" :label="val" :disabled="enAble">{{ val }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="套餐颜色:" prop="color">
        <div v-for="(item, index) in colorList" :key="index">
            <el-input v-model="item.color" style="width:15%;margin-bottom:5px;margin-left:5px;float: left;"
                placeholder="颜色,如红色" :readonly="isRead"></el-input>
        </div>
        <el-button icon="el-icon-plus" size="small" type="primary" class="add_btn" v-show="is_setmeal" @click="addColor"></el-button>
        <el-button icon="el-icon-minus" size="small" type="primary" class="add_btn" v-show="is_setmeal" @click="reductColor(index)">
        </el-button>
      </el-form-item>
      <el-form-item label="套餐规格:" prop="spec" >
        <template>
          <el-input 
          v-for="(item, index) in specList" :key="index" 
          v-model="item.spec" 
          style="width:60%;margin-bottom:5px;"
          placeholder="请输入套餐规格，如256G" :readonly="isRead"></el-input>
          <el-button icon="el-icon-plus" size="small" type="primary" class="add_btn" v-show="is_setmeal" @click="addSpec"></el-button>
          <el-button icon="el-icon-minus" size="small" type="primary" class="add_btn" v-show="is_setmeal" @click="reductSpec(index)">
          </el-button>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button 
          v-show="is_show" 
          icon="el-icon-plus" 
          size="small" 
          type="primary" 
          class="add_btn" 
          style="margin-left: 0;"
          @click="createMeal">生成套餐</el-button>
          <el-button 
          icon="el-icon-edit" 
          size="small" 
          type="primary" 
          class="add_btn" 
          style="margin-left: 10px;"
          @click="updateMeal">修改套餐</el-button>
      </el-form-item>
      <div v-show="is_meal" v-for="(item, index) in meal_list" :key="index">
        <el-form-item>
          <h5 style="color:#2993ff;">套餐{{ index + 1 }}：{{ item.title }}</h5>
        </el-form-item>
        <el-form-item label="套餐商品图片:" prop="meal_img">
          <crop-upload ref="coverUpload" show-type="photo" :fixScale="true" :is-square="true" :always-crop="true"
            :fixedBox="false" :init-val="item.meal_img" :type="meal" wrapper-width="120px" wrapper-height="120px" :photo-width="120"
            :photo-height="120" :autoCropWidth="150" :autoCropHeight="150" cropperWidth="400px" cropperHeight="400px"
            dialogWidth="600px" 
            :min-width="150" 
            :min-height="150" 
            :enlarge="5" 
            :params="index" 
            @setVal="setUrl">
          </crop-upload>

          <div class="color-999">注：尺寸为150*150px及以上正方形，图片要求为纯白色底图
            <el-popover placement="right" width="400" trigger="hover">
              <div class="img_exp">
                <h5>商品封面图片示例</h5>
                <div class="exp_wrap">
                  <p class="item">
                    <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp1.png')"></el-image>
                    <span><i class="green-font el-icon-success"></i>推荐</span>
                  </p>
                  <p class="item">
                    <template>
                      <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp2.png')"></el-image>
                      <span><i class="red-font el-icon-error"></i>不推荐</span>
                    </template>
                  </p>
                  <p class="item">
                    <template>
                      <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp3.png')"></el-image>
                      <span><i class="red-font el-icon-error"></i>不推荐</span>
                    </template>
                  </p>
                </div>
                <p class="red-font">注：图片要求750*750像素以上的正方形图片；<br />注：上传封面图片要求纯白色底图；<br />注：精品纯白色底图可上首页推荐位！</p>
              </div>
              <el-button slot="reference" type="text">图片示例></el-button>
            </el-popover>
          </div>
        </el-form-item>
        <el-form-item label="基础信息:" prop="quantity">
          <p style="float: left;margin-left: 10px;margin-right: 10px;">库存</p>
          <el-input v-model="item.quantity" placeholder="库存" style="float: left;width: 12%;margin-right: 5px;" clearable />
          <p style="float: left;margin-left: 10px;margin-right: 10px;">官网价格</p>
          <div style="float: left;width: 20%;">
            <el-input v-model="item.price" style="width: 70%;" class="suffix_input" placeholder="官网价格" clearable />
            <span class="suffix">元</span>
          </div>
          <p style="float: left;margin-left: 10px;margin-right: 10px;">市场价</p>
          <div style="float: left;width: 20%;">
            <el-input v-model="item.buyout_amount" style="width: 70%;" class="suffix_input" placeholder="市场价" clearable />
            <span class="suffix">元</span>
          </div>
        </el-form-item>

          <div v-for="(val, Key) in item.pect_type" :key="Key" >
          <el-form-item :label="val && Key == 1 ? '租完归还/续租/买断:' : item.pect_type[Key]===undefined?'':'租完即送:'" prop="val" :class="'none' + (Key + 1)">
            <div v-for="(v, k) in val" :key="k" style="float: left;margin-bottom: 5px;width: 25%;">
              <div v-if="val && Key == 1">
                <p style="float: left;line-height: 40px;">{{ v.lease_name }} ：</p>
                <div style="float: left;width: 70%">
                  <el-input v-model="v.lease_price" style="width: 70%;" placeholder="日租金" clearable />
                  <span class="suffix">元</span>
                </div>
              </div>
              <div v-if="val && Key == 2">
                <p style="float: left;line-height: 40px;">{{ v.lease_name }} ：</p>
                <div style="float: left;width: 70%">
                  <el-input v-model="v.lease_price_2" style="width: 70%;" placeholder="日租金" clearable />
                  <span class="suffix">元</span>
                </div>
              </div>
            </div>
          </el-form-item>
        </div>
      </div>
      <br>

    </el-form>
    <div class="fix-footer-btns">
      <!-- <div class="flex justify-center align-center">
        <label style="margin-right:20px"><i class="required-icon" style="margin-right:5px">*</i>商品审核后状态:</label>
        <el-radio v-model="status" :label="1">商品上架</el-radio>
        <el-radio v-model="status" :label="2">商品下架</el-radio>
      </div>
      <el-divider></el-divider> -->
      <div>
        <template v-if="$route.name === 'goodsAdd'">
          <!-- <el-button
            size="small"
            v-if="$hasMethod('#saveMealDraft')"
            @click="saveToDraft"
          >保存草稿</el-button> -->
          <el-button size="small" class="blue_border" @click="returnTab">返回</el-button>
          <el-button v-if="draftId" size="small" class="blue_border" @click="addMeal(true)">保存套餐</el-button>
          <el-button v-if="!draftId && $hasMethod('#publish')" size="small" type="warning" @click="addMeal(true)">发布商品</el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import cropUpload from '@/components/cropUpload'
import { addSetmeal, getGoodsSetmealInfo, editGoodsSetmeal, getGoodsInfo } from '@/api/goods'

const leaseOptions = ['1天', '7天', '15天', '30天', '90天', '120天', '180天', '270天', '365天']
export default {
  components: { cropUpload },
  props: ['currentMeal', 'editId', 'draftId'],
  data() {
    return {
      submitForm: {
        checkedLease: ['365天'],
        colorList: [{}],
        meal_list: [],
        title: '',
        price: [{}],
        meal_img: '',
        colorOfSpec: ''
      },
      rules: {},
      colorList: [{}], // 颜色
      specList: [{}], // 规格
      goods_id: '', // 商品ID
      pect_type: [], // 租赁方式
      meal_list: [], // 生成套餐
      goodsId: '',
      status: 2,
      lease_list: leaseOptions, // 租期
      checkedLease: ['365天'], // 默认显示租期
      meal_img: '', // 套餐商品图片
      setItemIdList: [],
      goods_name: '' // 商品名称
    }
  },
  watch: {
    currentMeal(val, oldVal) {
      this.getData()
    }
  },
  computed:{
    pactType:function(){
      return false
    }
  },
  mounted() {
    this.init()
    this.$nextTick(() => {
      if (this.$route.name === 'goodsMeal') {
        this.goodsId = this.$route.params.goodsId
        if (this.editId) {
          this.getInfo()
        } else {
          this.rentType = this.$route.params.pact_type
        }
      } else {
        this.rentType = JSON.parse(sessionStorage.getItem('baseInfo')) ? JSON.parse(sessionStorage.getItem('baseInfo')).formData.pact_type : 0
        this.goodsId = sessionStorage.getItem('goodsId') || ''
        this.getData()
      }
    })
  },
  beforeDestroy() {
    if (this.$route.name === 'goodsAdd') {
      this.saveStorage(this.currentMeal)
    }
  },
  methods: {
    // 生成套餐
    createMeal() {
      
      if(this.colorList[0].color === undefined&&this.specList[0].spec === undefined){
        this.$message({
            message: '套餐颜色或套餐规格不能为空，请重新生成！',
            type: 'error'
        })
        this.is_meal = false
      } else {
        sessionStorage.setItem('pact_type', this.pect_type)
        this.meal_list = []
        var pect_type = sessionStorage.getItem('baseOfPactType')!=null ? sessionStorage.getItem('baseOfPactType').split(',') : this.pect_type
        var pect_type_2 = pect_type
        var colorList = JSON.parse(JSON.stringify(this.colorList))
        var specList = JSON.parse(JSON.stringify(this.specList))
        var checkedLease = this.draftId ? this.submitForm.checkedLease : JSON.parse(JSON.stringify(this.checkedLease))
        for (var j = 0; j < colorList.length; j++) {
          for (var k = 0; k < specList.length; k++) {
            var lease = []
            for (let i = 1; i <= checkedLease.length; i++) {
              lease.push({
                lease_name: checkedLease[i - 1],
                lease_price: '', // 固定租期
                lease_price_2: '', // 租完即送
                spec: specList[k]['spec'],
                color: colorList[j]['color']
              })
            }
            pect_type_2 = []
            for (var n = 0; n < pect_type.length; n++) {
              pect_type_2[JSON.parse(JSON.stringify(pect_type[n]))] = lease
            }
            this.meal_list.push({
              title: this.goods_name + ' ' + specList[k]['spec'] + ' ' + colorList[j]['color'],
              pect_type: pect_type_2,
              checkedLease: checkedLease,
              quantity: 0, // 库存
              price: '', // 官网价格
              lease: lease, // 租期对应价格和市场价
              meal_img: '', // 套餐商品图片
              buyout_amount: '', // 市场价
              pact_type:sessionStorage.getItem('baseOfPactType') !== null ? sessionStorage.getItem('baseOfPactType').split(','):this.pect_type
            })
          }
        }
        this.is_meal = true
        this.is_show = false
        this.is_setmeal = false
        this.enAble = true
        this.isRead = true
      }
    },
    // 修改套餐
    updateMeal(){
      this.is_show = true
      this.is_setmeal = true
      this.enAble = false
      this.isRead = false
      sessionStorage.setItem('pact_type', this.pect_type)
      this.meal_list = []
      var pect_type = sessionStorage.getItem('baseOfPactType')!== null ? sessionStorage.getItem('baseOfPactType').split(',') : this.pect_type
      var pect_type_2 = pect_type
      var colorList = JSON.parse(JSON.stringify(this.colorList))
      var specList = JSON.parse(JSON.stringify(this.specList))
      var checkedLease = this.draftId ? this.submitForm.checkedLease : JSON.parse(JSON.stringify(this.checkedLease))
      for (var j = 0; j < colorList.length; j++) {
        for (var k = 0; k < specList.length; k++) {
          var lease = []
          for (let i = 1; i <= checkedLease.length; i++) {
            lease.push({
              lease_name: checkedLease[i - 1],
              lease_price: '', // 固定租期
              lease_price_2: '', // 租完即送
              spec: specList[k]['spec'],
              color: colorList[j]['color']
            })
          }
          pect_type_2 = []
          for (var n = 0; n < pect_type.length; n++) {
            pect_type_2[JSON.parse(JSON.stringify(pect_type[n]))] = lease
          }
          this.meal_list.push({
            title: this.goods_name + ' ' + specList[k]['spec'] + ' ' + colorList[j]['color'],
            pect_type: pect_type_2,
            checkedLease: checkedLease,
            quantity: 0, // 库存
            price: '', // 官网价格
            lease: lease, // 租期对应价格和市场价
            meal_img: '', // 套餐商品图片
            buyout_amount: '', // 市场价
            pact_type:sessionStorage.getItem('baseOfPactType') !=null ? sessionStorage.getItem('baseOfPactType').split(','):this.pect_type
          })
        }
      }
      this.is_meal = true
    },
    // 返回上一标签
    returnTab() {
      this.$emit('setTab', 'base')
    },
    setUrl(val) {
      if (this.meal_list[val[1]].meal_img === '') {
        this.meal_list[val[1]].meal_img = val[0]
      } else {
        this.meal_img = val[1]
        this.meal_list[val[1]].meal_img = ''
      }
    },
    // 保存草稿
    saveToDraft() {
      if (!this.goodsId) {
        this.$message({
          message: '请先提交商品基础信息',
          type: 'warning'
        })
        return
      }
      const params = { goods_id: this.goodsId, spec: this.meal_list, colorList: this.colorList, specList: this.specList, mealList: this.checkedLease, status: this.status, operation_type: 1 }
      if (params.setmeal_id) {
        params.mealList=Array.from(new Set(this.submitForm.checkedLease))
        // 存在套餐id，编辑套餐
        editGoodsSetmeal(params).then(res => {
          this.saveStorage()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        })
      } else {
        // 不存在套餐id，添加套餐
        delete params.setmeal_id
        addSetmeal(params).then(res => {
          this.meal_list.setmeal_id = res.setmeal_id
          this.saveStorage()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        })
      }
    },
    // 添加
    addMeal(isPublish) {
      // 判断是否有商品id
      if (!this.goodsId) {
        this.$message({
          message: '请先提交商品基础信息',
          type: 'warning'
        })
        return
      }
      // 提交当前表单
      const params = { goods_id: this.goodsId, spec: this.meal_list, colorList: this.colorList, specList: this.specList, mealList: this.checkedLease, status: this.status, operation_type: (isPublish ? 2 : 3) }
      if (this.draftId) {
        // 存在套餐id，编辑套餐
        params.mealList=Array.from(new Set(this.submitForm.checkedLease))
        editGoodsSetmeal(params).then(res => {
          if (isPublish) {
            this.$router.push({ name: 'goodsSuccess', params: { goodsId: this.goodsId }})
          } else {
            this.saveStorage()
            this.$emit('addTab')
          }
        })
      } else {
        // 不存在套餐id，添加套餐
        addSetmeal(params).then(res => {
          if (isPublish) {
            this.$router.push({ name: 'goodsSuccess', params: { goodsId: this.goodsId }})
          } else {
            this.meal_list.setmeal_id = res.setmeal_id
            this.saveStorage()
            this.$emit('addTab')
          }
        })
      }
    },
    // 保留两位小数
    toFix2(calVal) {
      return (Math.round(calVal * 100) / 100).toFixed(2)
    },
    changeNumberInput(obj, key) {
      const pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
      // 不符合正整数时
      if (!pattern.test(obj[key])) {
        // input 框绑定的内容为空
        obj[key] = ''
      }
    },
    changeMoneyInput(obj, key) {
      const pattern = /^[0-9]+([.]{1}[0-9]{1,2})?$/ // 正数的正则表达式
      // 不符合正数时
      if (!pattern.test(obj[key])) {
        // input 框绑定的内容为空
        obj[key] = ''
      }
    },
    // 新增颜色
    addColor() {
      this.colorList.push({})
      this.meal_list.color.push({ color: '' })
    },
    // 删除颜色
    reductColor(index) {
      if (this.colorList.length > 1) {
        this.colorList.pop(index, 1)
        this.meal_list.color.pop(index, 1)
      }
    },
    // 新增规格
    addSpec() {
      this.specList.push({})
      this.meal_list.spec.push({ spec: '' })
    },
    // 删除规格
    reductSpec(index) {
      if (this.specList.length > 1) {
        this.specList.pop(index, 1)
        this.meal_list.spec.pop(index, 1)
      }
    },
    init() {
      this.is_show = true
      this.is_setmeal = true
      this.enAble = false
      this.isRead = false
      this.goods_id = sessionStorage.getItem('goodsId')
      getGoodsInfo(this.goods_id).then(res => {
        // console.log('setMealInfo=>', res)
		if (res.setmeal.length === 0) {

        } else {
          res.meal.forEach((item) => {
            this.setItemIdList.push(item.setmeal_id)
          })
          if (this.draftId) {
            this.submitForm.checkedLease=[]
            this.is_meal = true
            this.is_show = false
            this.is_setmeal = false
            this.enAble = true
            this.isRead = true
            for (const key in this.submitForm) {
              
              if (key === 'checkedLease') {
                this.checkedLease=[]
                if(res.setmeal[0].pect_type[1]===undefined){
                  res.setmeal[0].pect_type[2].forEach(item => {
                    this.submitForm.checkedLease.push(item.lease_name)
                  })
                  this.submitForm.checkedLease=Array.from(new Set(this.submitForm.checkedLease))
                }else{
                  res.setmeal[0].pect_type[1].forEach(item => {
                    this.submitForm.checkedLease.push(item.lease_name)
                  })
                  this.submitForm.checkedLease=Array.from(new Set(this.submitForm.checkedLease))
                }
                
              } else if (key === 'meal_list') {
                // this.submitForm.meal_list = this.createMeal()
              } else if (key === 'title') {
                this.submitForm.title = res.setmeal[0].title
              } else if (key === 'price') {
                const meList = res.setmeal
                this.meal_list = meList
                this.submitForm.price = meList
              } else if (key === 'colorOfSpec') {
                const color = []
                const spec = []
                if (res.attr.length !== 0) {
                  res.attr.forEach(item => {
                    if (item.type === 1) {
                      color.push({
                        color: item.value
                      })
                    } else if (item.type === 2) {
                      spec.push({
                        spec: item.value
                      })
                    }
                  })
                } else {
                  res.meal.forEach(item => {
                    color.push({
                      color: item.color
                    })
                    spec.push({
                      spec: item.spec
                    })
                  })
                }
                this.colorList = color.filter((element, index, self) => {
                  return self.findIndex(x => x.color === element.color) === index
                })
                this.specList = spec.filter((element, index, self) => {
                  return self.findIndex(x => x.spec === element.spec) === index
                })
              }
            }
          }
        }
	    sessionStorage.setItem('pactType', res.pact_type)
	    this.pect_type = this.draftId ? res.pact_type : sessionStorage.getItem('baseOfPactType').split(',')
        this.goods_name = res.title
      })
    },
    getData() {
      this.meal_list = {
        setmeal_id: '',
        title: '',
        lease_set: 1,
        quantity: 0,
        is_buy_out: 1,
        price: ''
      }
      if (sessionStorage.getItem('mealInfo')) {
        const list = JSON.parse(sessionStorage.getItem('mealInfo'))
        if (list[this.currentMeal - 1]) {
          const data = list[this.currentMeal - 1]
          this.meal_list = { ...data.formData }
          this.monthList = [...data.monthList]
          this.dayList = [...data.dayList]
          this.customList = [...data.customList]
        }
        this.status = parseInt(sessionStorage.getItem('goodsStatus'))
      }
    },
    saveStorage(index) {
      const params = { formData: this.meal_list, monthList: this.monthList, dayList: this.dayList, customList: this.customList }
      const list = sessionStorage.getItem('mealInfo') ? JSON.parse(sessionStorage.getItem('mealInfo')) : []
      list[index - 1] = { ...params }
      sessionStorage.setItem('mealInfo', JSON.stringify(list))
      sessionStorage.setItem('goodsStatus', this.status)
    },
    getInfo() {
      getGoodsSetmealInfo(this.editId).then(res => {
        for (const key in this.meal_list) {
          if (key === 'setmeal_id') {
            this.meal_list[key] = res.id
          } else {
            this.meal_list[key] = res[key]
          }
        }
        this.rentType = res.pact_type
        this.status = res.goods_status
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.meal_form {
  padding: 30px 120px 30px 0;
}

.set_wrap {
  padding: 20px;
  background-color: #fafafa;
}

.set_form {
  border-bottom: 1px dashed #cdcdcd;
  margin-bottom: 16px;

  .item {
    margin-bottom: 16px;
  }

  .el-select,
  .el-input {
    width: 160px;
  }
}

label {
  margin-right: 14px;
}

.required-icon {
  margin-right: 3px;
}

.add_btn {
  // margin-left: 50px;
  margin-left: 10px;
}

.suffix {
  background: #f5f5f5;
  border: 1px solid #dcdfe6;
  border-radius: 0 4px 4px 0;
  height: 40px;
  display: inline-block;
  padding: 0 8px;
  box-sizing: border-box;
  border-left: none;
  line-height: 38px;
}

.suffix.before {
  border-left: 1px solid #dcdfe6;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.day_form {
  /deep/.el-input__inner {
    border-radius: 4px 0 0 4px;
  }
}

.custom_form {
  margin-top: 8px;
  margin-bottom: 8px;

  /deep/.el-input__inner,
  .el-select {
    border-radius: 0 4px 4px 0;
  }

  .no_border /deep/.el-input__inner {
    border-radius: 0;
  }

  &>div {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.custom_item+.custom_item {
  border-top: 1px dashed #cdcdcd;
  margin-top: 20px;
}

.table_item {
  /deep/th {
    padding: 0;
  }

  .suffix {
    height: 30px;
    line-height: 28px;
  }

  /deep/.el-input__inner {
    border-radius: 4px 0 0 4px;
  }

  /deep/.el-input__icon {
    line-height: 30px;
  }
}

.suffix_input {
  /deep/.el-input__inner {
    border-radius: 4px 0 0 4px;
  }
}

.delete_btn {
  position: absolute;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 70px;
  border: 1px solid #ebeef5;
  border-left: none;
  background-color: #ffffff;
}

.tip {
  color: #999999;
  line-height: 35px;
}

.set_table {
  /deep/th {
    padding: 0;
  }

  /deep/.el-input__icon {
    line-height: 30px;
  }
}

.fix-footer-btns {
  .el-divider {
    background-color: #eeeeee;
    width: 95%;
    margin: 15px auto;
  }
}
.none1 {
  display: none;
}
</style>
